import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'

Vue.use(VueRouter)

// 点击路由重复报错解决方案
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    },
    children: [
      {
        path: '/searchPopup',
        name: 'SearchPopup',
        component: () => import('@/views/SearchPopup.vue')
      }
    ]
  },
  {
    path: '/special',
    name: 'Special',
    component: () => import('@/views/Special/Special.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/brandDetail',
    name: 'BrandDetail',
    component: () => import('@/views/BrandDetail/BrandDetail.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: false
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('@/views/Category/Category.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/list',
    name: 'List',
    component: () => import('@/views/List/List.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/Cart/Cart.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('@/views/User/User.vue'),
    // 控制Tabbar显示，true为显示
    meta: {
      isShowTabbar: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/Login.vue')
  },
  {
    path: '/productsDetail',
    name: 'ProductsDetail',
    component: () => import('@/views/ProductsDetail/ProductsDetail.vue')
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // 要去往的路由对象
  // console.log('to', to)
  // 从哪里出发的路由对象
  // console.log('from', from)
  // 获取token
  const token = localStorage.getItem('token')
  // 表示要去购物车页面
  if (to.path === '/cart') {
    // 判断有没有登录，判断token是否存在
    if (token) {
      next()
    } else {
      // 表示没有登录
      Vue.prototype.$toast('请先登录')
      // 延迟1s跳转
      setTimeout(() => {
        // 跳转到会员中心页面
        next('/user')
      }, 500)
    }
  }
  // 可以顺利通过要去的路由，如果不写next()，就不能访问到对应的路由
  next()
})

export default router
